<template>
  <div class="menu">
    <div class="search">
      <el-input placeholder="输入关键字查找菜单" v-model="filterText">
      </el-input>
    </div>
    <el-button-group class="operation">
      <el-button type="primary" @click="append({}, 'main')">添加主菜单</el-button>
      <!-- <el-button type="primary" @click="switchDrag()">{{
        draggable ? "确认排序" : "开启排序"
      }}</el-button> -->
    </el-button-group>
    <el-tree
      ref="tree"
      :data="data"
      node-key="id"
      default-expand-all
      label="name"
      :props="treeProps"
      :filter-node-method="filterNode"
      :expand-on-click-node="false"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" size="mini" @click="() => append(data, 'add')">
            +加子菜单
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => append(data, 'edit')"
          >
            编辑
          </el-button>
          <el-button type="text" size="mini" @click="() => remove(node, data)">
            禁用
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-drawer
      title="添加/编辑菜单"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="drawerHandleClose"
    >
      <div class="drawer-main">
        <el-form
          label-position="top"
          label-width="80px"
          ref="ruleForm"
          :rules="rules"
          :model="formData"
        >
          <el-form-item label="菜单名称" required prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="路由" prop="path">
            <el-input v-model="formData.path"></el-input>
          </el-form-item>
          <el-form-item label="ICON">
            <el-input v-model="formData.icon"></el-input>
          </el-form-item>
          <!-- <el-form-item label="权限" required>
            <el-select style="width: 100%" v-model="formData.permission" multiple placeholder="请选择">
              <el-option
                v-for="(item, index) in restaurants"
                :key="index"
                :label="item.name"
                :value="item.id"
                >
                {{ item.name }}
              </el-option>
            </el-select>

          </el-form-item> -->

          <el-form-item label="排序">
            <el-input v-model="formData.sort" placeholder="请输入数字进行正序排列，如：1，2"></el-input>
          </el-form-item>

          <el-form-item label="是否占用菜单位" prop="resource">
            <el-radio-group v-model="formData.isShowLeft ">
              <el-radio label="是" value="1"></el-radio>
              <el-radio label="否" value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              round
              style="width: 100%"
              @click.stop="addOrEdit"
              >提交</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>

const formData = {
  name: '',
  path: '',
  icon: '',
  permission: '',
  isShowLeft: '1',
  sort: null
}
export default {
  data () {
    return {
      treeProps: {
        children: 'childrens',
        label: 'name'
      },
      data: [],
      filterText: '',
      draggable: false,
      drawer: false,
      formData: JSON.parse(JSON.stringify(formData)),
      loading: false,
      currentTree: null,
      rules: {
      },
      permissionItem: null,
      restaurants: [], // 权限列表
      drawerTitle: '',
      nowType: ''
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getOperateMenus()
    this.querySearchAsync()
  },
  methods: {
     // 获取权限列表
    async querySearchAsync() {
      let res = await this.$http.post('/account/selectAdminPrivilege', {
      })
      if (res.code === '0') {
        this.restaurants = res.data
        return
      }
      this.$message({
          type: 'error',
          message: '系统异常，请稍后再试'
      })
    },
    // 获取全部菜单列表
    async getOperateMenus() {
      let res = await this.$http.post('/account/getOperateMenus', {
      })
      if (res.code === '0') {
        this.getOutSideMenuList()
        this.data = JSON.parse(JSON.stringify(res.data))
        return
      }
      this.$message({
          type: 'error',
          message: '系统异常，请稍后再试'
      })
    },
    // 获取外部菜单
    async getOutSideMenuList () {
        let res = await this.$http.post('/account/menus')
        if (res.code === '0') {
            this.$store.commit('changeSideBar', res.data);
            return
        }
        this.$message({
            type: 'error',
            message: '系统异常，请稍后再试'
        })
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    append (data, type) {
      this.drawer = true
      this.nowType = type
      if (type === 'main') { this.currentTree = null }
      if (type === 'add') { this.currentTree = data }

      if (type !== 'edit') {
        this.formData = {
          name: '',
          path: '',
          icon: '',
          permission: '',
          isShowLeft: '1',
          sort: null
        }
        return
      }

      if (type === 'edit') {
        this.formData = data
        this.formData.isShowLeft = data.isShowLeft === 0 ? '否' : '是'
      }
      this.currentTree = data
    },

    remove (node, data) {
      // const parent = node.parent
      // const children = parent.data.childrens || parent.data
      // const index = children.findIndex((d) => d.id === data.id)
      // children.splice(index, 1)
      this.updateMenuStatus(data.id)
    },

    async updateMenuStatus(id) {
      let params = {
        id,
        status: 0
      }
      let res = await this.$http.post('/account/updateMenuStatus',  params)
      if (res.code === '0') {
        this.getOperateMenus()
        return
      }
      this.$message({
          type: 'error',
          message: '系统异常，请稍后再试'
      })
    },
    switchDrag () {
      this.draggable = !this.draggable
    },
    drawerHandleClose () {
      this.refresh()
    },
    refresh () {
          this.drawer = false
          this.currentTree = null
          this.getOperateMenus()
          // this.formData = JSON.parse(JSON.stringify(formData))
    },
    addOrEdit () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let data = this.currentTree || {}
          let newChild = {
            ...this.formData
          }
          // 如果有data则是添加、编辑子菜单
          if (data) {
            newChild.id = data.id
          }
          this.createMenus(newChild, data)
          this.refresh()
        } else {
          return false
        }
      })
    },
    // 创建菜单
    async createMenus(item, data) {
      let adminMenuPrivilegeList = []
      // item.permission && item.permission.forEach((it) => {
      //   adminMenuPrivilegeList.push({
      //     id: null,
      //     menuid: null,
      //     privilegeRef: it
      //   })
      // })
      let adminMenu = {
          ...data,
          ...item
      }
      // 一级菜单
      if (this.nowType === 'main') {
        adminMenu.level1 = 0
        adminMenu.level2 = 0
      }

      // delete adminMenu.permission
      // 如果不是编辑则删除 id
      if (this.nowType !== 'edit') {
        delete adminMenu.id
      }
      adminMenu.isShowLeft = item.isShowLeft === '是' ? 1 : 0


      let res = await this.$http.post('/account/createMenus', { adminMenu, adminMenuPrivilegeList })
      if (res.code === '0') {
        this.getOperateMenus()
        return
      }
      this.$message({
          type: 'error',
          message: '系统异常，请稍后再试'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.menu {
  .search {
    padding: 15px 15px 0 15px;
  }
  .operation {
    margin: 15px;
  }
  .drawer-main {
    padding: 0 20px;
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
/deep/ .el-drawer__wrapper {
  *:focus {
    outline: none;
  }
}
</style>